/*
 * Copyright (c) 2018 maoyan.com
 * All rights reserved.
 *
 */
package com.darren.euc.service.impl;

import com.darren.euc.dao.ActivityMemberRelDao;
import com.darren.euc.dao.ClientDao;
import com.darren.euc.dao.MemberDao;
import com.darren.euc.entity.*;
import com.darren.euc.repository.ActivityMemberRelRepository;
import com.darren.euc.repository.ClientRepository;
import com.darren.euc.service.ActivityMemberRelService;
import com.darren.euc.util.StringUtil;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 在这里编写类的功能描述
 *
 * @author fangwenhao
 * @created 2018/3/11
 */
@Service
public class ActivityMemberRelServiceImpl implements ActivityMemberRelService {

    @Autowired
    private ClientDao clientDao;

    @Autowired
    private MemberDao memberDao;

    @Autowired
    private ActivityMemberRelDao activityMemberRelDao;

    @Autowired
    private ClientRepository clientRepository;

    @Autowired
    private ActivityMemberRelRepository activityMemberRelRepository;


    @Override
    public PageBean queryForPageActivityMemberRelHQL(JSONObject data, Integer pageSize, int currentPage) {
        String name = data.getString("name");
        String mobile = data.getString("mobile");
        Long activityId = data.getLong("activityId");
        //page从0开始算
        currentPage = --currentPage;
        if(currentPage<0)
            return null;
        if(activityId<1)
            return null;
        List<Member> members = new ArrayList<>();
        String HQL = "select m from Member m,ActivityMemberRel ar where 1=1 and m.id = ar.memberId and ar.activityId="+activityId+" ";
        if(!StringUtil.isEmptyOrWhitespace(name) && !StringUtil.isEmptyOrWhitespace(mobile)){
            HQL = HQL + " and name = ? and mobile = ? ";
            members = memberDao.queryByCondition(HQL,name,mobile);
        }else if (!StringUtil.isEmptyOrWhitespace(name) && StringUtil.isEmptyOrWhitespace(mobile)){
            HQL = HQL + " and name = ?";
            members = memberDao.queryByCondition(HQL,name);
        }else if (StringUtil.isEmptyOrWhitespace(name) && !StringUtil.isEmptyOrWhitespace(mobile)){
            HQL = HQL + " and mobile = ?";
            members = memberDao.queryByCondition(HQL,mobile);
        }else {
            members = memberDao.queryByCondition(HQL);
        }
        List<Long> memberIds = new ArrayList<>();
        Set<Integer> userIds  = new HashSet<>();
        if (members.size() > 0){
            memberIds = members.stream().map(Member::getId).map(item->Long.valueOf(item)).collect(Collectors.toList());
            userIds = members.stream().map(Member::getClientId).collect(Collectors.toSet());
          //  Iterator<Integer> iterator = userIds.iterator();
//            while(iterator.hasNext()){
//                if(iterator.next() == null){
//                    iterator.remove();
//                }
//            }
            userIds.removeIf( number -> number == null);
            memberIds.removeIf(number -> number == null);
        }
        List<Client> clientList =  clientRepository.findByIdIn(userIds);
        PageBean pageBean = new PageBean();
        Page<ActivityMemberRel> activityMemberRelPage = activityMemberRelRepository.findByActivityIdAndMemberIdIn(activityId,memberIds,new PageRequest(currentPage,pageSize));
        pageBean.setList(activityMemberRelPage.getContent());
        pageBean.setPageSize(pageSize);
        pageBean.setCurrentPage(currentPage);
        pageBean.setTotalPage(activityMemberRelPage.getTotalPages());
        pageBean.setTotalRow(Long.valueOf(activityMemberRelPage.getTotalElements()).intValue());
        List<ActivityMemberRel> activityMemberRelList = pageBean.getList();
        List<ActivityMember> activityMemberList = new ArrayList<>();
        for (ActivityMemberRel activityMemberRel : activityMemberRelList) {
            ActivityMember activityMember = new ActivityMember();
            activityMember.setId(activityMemberRel.getId());
            activityMember.setActivityId(activityMemberRel.getActivityId());
            activityMember.setMemberId(activityMemberRel.getMemberId());
            Optional<Member> memberOptional = members.stream().filter(member -> member.getId().longValue() == activityMemberRel.getMemberId()).findFirst();
            activityMember.setMobile(memberOptional.get().getMobile());
            activityMember.setName(memberOptional.get().getName());
            activityMember.setUserId(memberOptional.get().getClientId());
            Optional<Client> clientOptional = clientList.stream().filter(client -> client.getId().equals(activityMember.getUserId())).findFirst();
            try{
                activityMember.setUserName(clientOptional.get().getCompanyName());
            }catch(Exception e ){
                e.printStackTrace();
                activityMember.setUserName("unkown");
            }
            activityMember.setAddTime(activityMemberRel.getAddTime());
            activityMember.setIsCheck(activityMemberRel.getIsCheck());
            activityMemberList.add(activityMember);
        }
        pageBean.setList(activityMemberList);
        return pageBean;
    }

    @Override
    public ActivityMemberRel updateCheck(Long id) {
        ActivityMemberRel activityMemberRel = activityMemberRelDao.findById(id);
        activityMemberRel.setIsCheck(1);
        return activityMemberRelDao.save(activityMemberRel);
    }

    @Override
    public ActivityMemberRel save(ActivityMemberRel activityMemberRel) {
        return activityMemberRelDao.save(activityMemberRel);
    }

    @Override
    public List<ActivityMemberRel> findByActivityId(Long activityId) {
        String Hql = " from ActivityMemberRel where activityId = ? ";
        return activityMemberRelDao.queryByCondition(Hql,activityId);
    }

    @Override
    public List<ActivityMemberRel> findByMemberIdAndStatusIn(Long memId, List<Integer> statuses) {
        return activityMemberRelRepository.findByMemberIdAndStatusIn(memId, statuses);
    }

    @Override
    public ActivityMemberRel findByActivityIdAndMemberId(Long activityId, Integer memberId) {
        return activityMemberRelRepository.findByActivityIdAndMemberId(activityId,Integer.toUnsignedLong(memberId));
    }

}
